package renda.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import renda.dao.BaseDAO;
import renda.dao.TopicChildDAO;
import renda.pojo.Topicchild;

@Repository("topicChildDAO")
@Transactional
public class TopicChildDAOImpl extends BaseDAO implements TopicChildDAO {

	@SuppressWarnings("unchecked")
	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	public List<Topicchild> listByTopicId(final Integer topicsId, final int offset, final int length) {
		List executeFind = getTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException, SQLException {
				Integer topicsId2 = topicsId != null ? topicsId : -1;
				StringBuilder hql = new StringBuilder("from Topicchild tc where tc.topicid = ");
				hql.append(topicsId2).append(" order by tc.tcid desc");
				Query query = session.createQuery(hql.toString());
				// System.out.println("query = " + query);
				query.setFirstResult(offset);
				query.setMaxResults(length);
				List list2 = query.list();
				return list2;
			}
		});
		List<Topicchild> topicchilds = executeFind;
		return topicchilds;
	}

	@Transactional(propagation = Propagation.REQUIRED)
	public Topicchild saveTopicchild(Topicchild topicchild) {
		/* topicchild = (Topicchild) */getTemplate().save(topicchild);
		return topicchild;
	}

	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	public int countTopicchild(Integer topicsId) {
		Integer topicsId2 = topicsId != null ? topicsId : -1;
		StringBuilder hql = new StringBuilder("select count(tc.tcid) from Topicchild tc where tc.topicid = ");
		hql.append(topicsId2);
		System.out.println("hql = " + hql.toString());
		Long count = (Long) getTemplate().find(hql.toString()).listIterator().next();
		count = count == null ? 0L : count;
		return count.intValue();
	}

}
